import { Component, OnInit } from '@angular/core';

import { ModalController, NavParams } from '@ionic/angular';

@Component({
  selector: 'app-modal-of-person-search',
  templateUrl: './modal-of-person-search.component.html',
  styleUrls: ['./modal-of-person-search.component.scss'],
})
export class ModalOfPersonSearchComponent implements OnInit {

  keyword = '';   // 搜索关键词
  hasSearched: Boolean = false;     // 是否已经搜索
  searchArr: any[];       // 搜索历史记录数组
  tagData: any;
  searchType: any;
  searchBtnColor = '#858894';
  listId: any; // 搜索相应的列表用的id
  constructor(
    private navParams: NavParams,
    private modalCtrl: ModalController,
  ) { }

  ngOnInit() {
    if (this.navParams.data.value.sarchPerson) {
      this.searchType = 'searchPerson';
      this.searchArr = JSON.parse(localStorage.getItem(this.searchType))
        ? JSON.parse(localStorage.getItem(this.searchType)) : [];
    }
  }
  focusInput() {
    this.hasSearched = false;
    this.keyword = '';
  }

  searchChange() {
    if (this.keyword === '') {
      this.searchBtnColor = '#858894';
    } else {
      this.searchBtnColor = '#27282E';
    }
  }
  search(str) {

    if (str === '' && this.keyword === '') {
      return;
    }
    // this.hasSearched = true;
    const len = this.searchArr.length;
    if (!str) {
      if (this.keyword !== '' && this.searchArr.indexOf(this.keyword) === -1) {
        this.searchArr.unshift(this.keyword);
        if (len >= 10) {
          this.searchArr.pop();
        }
        localStorage.setItem(this.searchType, JSON.stringify(this.searchArr));
      }
    } else {
      this.keyword = str;
    }
    this.modalCtrl.dismiss({data: this.keyword});
  }

  back() {
    this.modalCtrl.dismiss();
  }

  clearHistory() {
    this.searchArr = [];
    localStorage.removeItem(this.searchType);
  }
}
